package com.tenement.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tenement.entity.UserTenement;
import com.tenement.mapper.UserTenementMapper;
import com.tenement.service.UserTenementService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.tenement.entity.table.UserTenementTableDef.USER_TENEMENT;

/**
 *  服务层实现。
 *
 * @author BertXie
 * @since 1.0.1
 */
@Service
@RequiredArgsConstructor
public class UserTenementServiceImpl extends ServiceImpl<UserTenementMapper, UserTenement> implements UserTenementService {

    private final UserTenementMapper userTenementMapper;

    @Override
    public int operator(UserTenement userTenement) {
        QueryWrapper userTenementWrapper = QueryWrapper.create()
                .from(USER_TENEMENT)
                .where(USER_TENEMENT.USER_ID.eq(userTenement.getUserId())
                        .and(USER_TENEMENT.TENEMENT_ID.eq(userTenement.getTenementId()))
                );
        userTenementMapper.deleteByQuery(userTenementWrapper);
        return userTenementMapper.insertSelective(userTenement);
    }

    @Override
    public long exists(Long userId) {
        return userTenementMapper.selectCountByQuery(QueryWrapper.create().from(USER_TENEMENT).where(USER_TENEMENT.USER_ID.eq(userId)));
    }

    @Override
    public List<Long> tenementIds(Long userId) {
        return userTenementMapper.selectListByQueryAs(QueryWrapper.create().from(USER_TENEMENT)
                .select(USER_TENEMENT.TENEMENT_ID)
                .where(USER_TENEMENT.USER_ID.eq(userId)),Long.class);
    }
}
